import { sendTo, useCurrentUser, useReqBody, useSend, useUpload } from "@sker/runtime";
import { HttpError, currentUsers, toSuccess, useTransaction } from "@sker/core";
import dayjs from "dayjs";
import { randomBytes } from "crypto";
import { extname } from "path";
import { z } from "zod";
import { SysUser, SysUserMessage } from "@sker/entities";

export const send = async () => {
    const input = z.object({
        from_username: z.string(),
        to_username: z.string(),
        type: z.string(),
        body: z.any()
    })
    const body = input.parse(useReqBody())
    await useTransaction(async (m) => {
        const entity = m.create(SysUserMessage, { ...body, readed: false })
        await m.save(SysUserMessage, entity)
        const to = await m.findOne(SysUser, { where: { username: body.to_username }, select: { uid: true } })
        const count = await m.count(SysUserMessage, { where: { to_username: body.to_username } })
        sendTo(to.uid, JSON.stringify({
            type: 'layout',
            payload: {
                count: count
            }
        }))
    })
    return toSuccess({})
}

export const upload = async () => {
    const url = await useUpload(m => {
        const ext = extname(m.filename)
        if (['.jpg', '.jpeg', '.png'].includes(ext.toLocaleLowerCase())) {
            return `images/${dayjs().format('YYYY/MM/DD')}/${parseInt(`${Math.random() * 1000000}`, 10)}${randomBytes(8).toString('base64')}${ext}`
        } else {
            throw new HttpError(`不支持此后缀名文件，请上传.jpg/.jpeg/.png图片`)
        }
    })
    return toSuccess(url)
}
/**
 * 系统消息
 */
export const ws = async (msg: any) => {
    useSend(JSON.stringify(msg))
    const [currentUser] = useCurrentUser(true)
    let currentUid = currentUser?.uid;
    if (!(currentUid && currentUid.length > 0)) return;
    const count = await useTransaction(async m => {
        const sysUser = await m.findOne(SysUser, { where: { uid: currentUid }, select: { username: true } })
        if (!sysUser) throw new HttpError(`登录失效`)
        const count = await m.count(SysUserMessage, { where: { to_username: sysUser.username } })
        return count;
    })
    useSend(JSON.stringify({
        type: 'layout',
        payload: {
            count: count
        }
    }))
}
